package com.sunday.authorization.security.authentication.token;

import com.sunday.authorization.security.tools.userdetails.UserInfo;
import com.sunday.authorization.security.userdetails.CustomUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;

import java.util.Map;

/**
 * @author sunday
 * @see org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer
 * @see org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.DefaultOAuth2TokenCustomizers
 * @see org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2ConfigurerUtils#getJwtCustomizer(HttpSecurity)
 * @see org.springframework.security.oauth2.server.authorization.token.JwtGenerator#generate(OAuth2TokenContext)
 * @since 2024/9/18
 */
public class CustomOAuth2TokenCustomizer {


    public static OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
        return (context) -> context.getClaims().claims((claims) -> customize(context, claims));
    }

    private static void customize(OAuth2TokenContext tokenContext, Map<String, Object> claims) {

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = tokenContext.getPrincipal();
        if(usernamePasswordAuthenticationToken.getPrincipal() instanceof CustomUser customUser){
            UserInfo userInfo = customUser.getUserInfo();
            claims.put("id", userInfo.getId());
            claims.put("permission", userInfo.getPermissionsSum());
        }

    }


}
